/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.tompai.common.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.tompai.common.utils.MsgResult;

@RestController
public class MainsiteErrorController implements ErrorController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private static final String ERROR_PATH = "/error";

	@Autowired
	ErrorAttributes errorAttributes;

	@RequestMapping(value = { ERROR_PATH }, produces = { "text/html" })
	public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
		int code = response.getStatus();
		if (404 == code) {
			return new ModelAndView("error/404");
		} else if (403 == code) {
			return new ModelAndView("error/403");
		} else if (401 == code) {
			return new ModelAndView("login");
		} else {
			return new ModelAndView("error/500");
		}

	}

	@RequestMapping(value = ERROR_PATH)
	public MsgResult handleError(HttpServletRequest request, HttpServletResponse response) {
		response.setStatus(200);
		int code = response.getStatus();
		if (404 == code) {
			return MsgResult.error(404, "未找到资源");
		} else if (403 == code) {
			return MsgResult.error(403, "没有访问权限");
		} else if (401 == code) {
			return MsgResult.error(403, "登录过期");
		} else {
			return MsgResult.error(500, "服务器错误");
		}
	}

	@Override
	public String getErrorPath() {
		// TODO Auto-generated method stub
		return ERROR_PATH;
	}
}